package com.daxia.ogmall.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.daxia.ogmall.common.HouseAreaTag;
import com.daxia.ogmall.common.UserDesignStatus;
import com.daxia.ogmall.daobase.GenericDAOHibernate;
import com.daxia.ogmall.dto.UserDesignDTO;
import com.daxia.ogmall.model.UserDesign;
import com.daxia.ogmall.support.Page;

@Repository
public class UserDesignDAO extends GenericDAOHibernate<UserDesign> {

    public List<UserDesign> find(UserDesignDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From UserDesign n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (dto.getCommunity() != null) {
        	if (dto.getCommunity().getId() != null) {
	            hql.append(" and n.community.id = ? ");
	            paras.add(dto.getCommunity().getId());
        	}
        }			
        if (dto.getHouseType() != null) {
        	if (dto.getHouseType().getId() != null) {
	            hql.append(" and n.houseType.id = ? ");
	            paras.add(dto.getHouseType().getId());
        	}
        }			
        if (dto.getHouseStyle() != null) {
        	if (dto.getHouseStyle().getId() != null) {
	            hql.append(" and n.houseStyle.id = ? ");
	            paras.add(dto.getHouseStyle().getId());
        	}
        }			
        if (StringUtils.isNotBlank(dto.getName())) {
            hql.append(" and n.name like ? ");
            paras.add("%" + dto.getName() + "%");
        }					
        if (dto.getUser() != null) {
        	if (dto.getUser().getId() != null) {
	            hql.append(" and n.user.id = ? ");
	            paras.add(dto.getUser().getId());
        	}
        }			
        if (dto.getStatus() != null) {
            hql.append(" and n.status = ? ");
            paras.add(dto.getStatus());
        }
        if (dto.getHouseAreaTag() != null) {
        	hql.append(" and n.area >= ? and n.area <= ? ");
        	paras.add(HouseAreaTag.getByValue(dto.getHouseAreaTag()).getMinArea()+"");
        	paras.add(HouseAreaTag.getByValue(dto.getHouseAreaTag()).getMaxArea()+"");
        }
        
        /*
        if (!dto.isAdmin()) {
        	hql.append(" and n.status = ? ");
        	paras.add(UserDesignStatus.Published.getValue());
        }*/
        
        hql.append(" order by n.id desc ");
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public UserDesign findOne(UserDesignDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<UserDesign> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }
}
